from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django.db.models import Q, Count, Avg, Sum
from django.utils import timezone
from datetime import timedelta
from typing import List, Dict, Any  # 添加类型导入
import json

from .models import TestReport, ReportDetail, Dashboard
from .serializers import (
    TestReportSerializer, ReportDetailSerializer, DashboardSerializer,
    ReportFilterSerializer, StatisticsSerializer
)
from users.permissions import IsReviewerOrAdmin


class TestReportViewSet(viewsets.ModelViewSet):
    serializer_class = TestReportSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        queryset = TestReport.objects.all()

        if user.role == 'user':
            queryset = queryset.filter(created_by=user)

        # 查询过滤
        report_type = self.request.query_params.get('report_type')
        start_date = self.request.query_params.get('start_date')
        end_date = self.request.query_params.get('end_date')
        status_filter = self.request.query_params.get('status')  # 重命名避免冲突

        if report_type:
            queryset = queryset.filter(report_type=report_type)
        if start_date:
            queryset = queryset.filter(created_at__date__gte=start_date)
        if end_date:
            queryset = queryset.filter(created_at__date__lte=end_date)
        if status_filter:  # 使用重命名后的变量
            queryset = queryset.filter(status=status_filter)

        return queryset.order_by('-created_at')

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['get'])
    def details(self, request, pk=None):
        """获取报告详情"""
        report = self.get_object()
        details = ReportDetail.objects.filter(report=report)
        serializer = ReportDetailSerializer(details, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取报告统计信息"""
        user = request.user
        queryset = TestReport.objects.all()

        if user.role == 'user':
            queryset = queryset.filter(created_by=user)

        # 基础统计
        total_reports = queryset.count()
        total_cases = queryset.aggregate(
            total=Sum('total_cases'),
            passed=Sum('passed_cases'),
            failed=Sum('failed_cases')
        )

        total_cases_count = total_cases['total'] or 0
        total_passed = total_cases['passed'] or 0
        total_failed = total_cases['failed'] or 0

        overall_pass_rate = 0
        if total_cases_count > 0:
            overall_pass_rate = (total_passed / total_cases_count) * 100

        # 最近报告 - 添加类型注解
        recent_reports_data: List[Dict[str, Any]] = list(queryset.order_by('-created_at')[:5].values(
            'id', 'name', 'status', 'pass_rate', 'created_at'
        ))

        data = {
            'total_reports': total_reports,
            'total_cases': total_cases_count,
            'total_passed': total_passed,
            'total_failed': total_failed,
            'overall_pass_rate': round(overall_pass_rate, 2),
            'recent_reports': recent_reports_data  # 使用重命名后的变量
        }

        serializer = StatisticsSerializer(data=data)
        serializer.is_valid()
        return Response(serializer.data)

    @action(detail=False, methods=['post'])
    def filter(self, request):
        """高级报告筛选"""
        serializer = ReportFilterSerializer(data=request.data)
        if serializer.is_valid():
            user = request.user
            queryset = TestReport.objects.all()

            if user.role == 'user':
                queryset = queryset.filter(created_by=user)

            filters = Q()
            if serializer.validated_data.get('report_type'):
                filters &= Q(report_type=serializer.validated_data['report_type'])
            if serializer.validated_data.get('start_date'):
                filters &= Q(created_at__date__gte=serializer.validated_data['start_date'])
            if serializer.validated_data.get('end_date'):
                filters &= Q(created_at__date__lte=serializer.validated_data['end_date'])
            if serializer.validated_data.get('status'):
                filters &= Q(status=serializer.validated_data['status'])

            reports = queryset.filter(filters).order_by('-created_at')
            page = self.paginate_queryset(reports)
            if page is not None:
                serializer = TestReportSerializer(page, many=True)
                return self.get_paginated_response(serializer.data)

            serializer = TestReportSerializer(reports, many=True)
            return Response(serializer.data)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class ReportDetailViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = ReportDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        queryset = ReportDetail.objects.all()

        if user.role == 'user':
            queryset = queryset.filter(report__created_by=user)

        report_id = self.request.query_params.get('report_id')
        if report_id:
            queryset = queryset.filter(report_id=report_id)

        return queryset


class DashboardViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = DashboardSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Dashboard.objects.all().order_by('-date')[:30]  # 最近30天数据

    @action(detail=False, methods=['get'])
    def overview(self, request):
        """仪表盘概览数据"""
        # UI测试统计
        ui_reports = TestReport.objects.filter(report_type__in=['ui_suite', 'ui_case'])
        ui_total = ui_reports.count()
        ui_passed = ui_reports.filter(status='passed').count()
        ui_failed = ui_reports.filter(status='failed').count()
        ui_pass_rate = (ui_passed / ui_total * 100) if ui_total > 0 else 0

        # API测试统计
        api_reports = TestReport.objects.filter(report_type__in=['api_suite', 'api_case'])
        api_total = api_reports.count()
        api_passed = api_reports.filter(status='passed').count()
        api_failed = api_reports.filter(status='failed').count()
        api_pass_rate = (api_passed / api_total * 100) if api_total > 0 else 0

        # 最近执行统计
        recent_reports_list = TestReport.objects.order_by('-created_at')[:10]  # 重命名变量

        # 今日统计
        today = timezone.now().date()
        today_reports = TestReport.objects.filter(created_at__date=today)
        today_total = today_reports.count()
        today_passed = today_reports.filter(status='passed').count()

        data = {
            'ui_statistics': {
                'total': ui_total,
                'passed': ui_passed,
                'failed': ui_failed,
                'pass_rate': round(ui_pass_rate, 2)
            },
            'api_statistics': {
                'total': api_total,
                'passed': api_passed,
                'failed': api_failed,
                'pass_rate': round(api_pass_rate, 2)
            },
            'today_statistics': {
                'total': today_total,
                'passed': today_passed,
                'pass_rate': round((today_passed / today_total * 100) if today_total > 0 else 0, 2)
            },
            'recent_reports': TestReportSerializer(recent_reports_list, many=True).data  # 使用重命名后的变量
        }

        return Response(data)


class ReportGeneratorView(APIView):
    """报告生成器"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """生成测试报告"""
        report_type = request.data.get('report_type')
        target_id = request.data.get('target_id')
        target_name = request.data.get('target_name')

        if not all([report_type, target_id, target_name]):
            return Response({'error': '缺少必要参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 模拟报告生成
        report_data = {
            'total_cases': 10,
            'passed_cases': 8,
            'failed_cases': 2,
            'skipped_cases': 0,
            'error_cases': 0,
            'start_time': timezone.now() - timedelta(minutes=5),
            'end_time': timezone.now(),
            'duration': 300.5,
            'execution_data': {
                'environment': '测试环境',
                'browser': 'chrome',
                'execution_mode': '自动'
            }
        }

        report = TestReport.objects.create(
            name=f"{target_name} - 测试报告",
            report_type=report_type,
            target_id=target_id,
            target_name=target_name,
            created_by=request.user,
            **report_data
        )

        # 生成报告详情
        for i in range(10):
            case_status = 'passed' if i < 8 else 'failed'  # 重命名变量
            ReportDetail.objects.create(
                report=report,
                case_name=f"测试用例 {i + 1}",
                case_type=report_type,
                status=case_status,  # 使用重命名后的变量
                duration=30.5,
                start_time=timezone.now() - timedelta(minutes=4),
                end_time=timezone.now() - timedelta(minutes=3, seconds=30),
                log=f"用例 {i + 1} 执行{'成功' if case_status == 'passed' else '失败'}",
                error_message="" if case_status == 'passed' else "断言失败: 期望值不匹配"
            )

        serializer = TestReportSerializer(report)
        return Response({
            'message': '报告生成成功',
            'report': serializer.data
        })